package com.shhm.system.service.impl;

import com.shhm.common.dto.response.AjaxResult;
import com.shhm.common.entity.system.SysMenu;
import com.shhm.common.entity.system.UserRole;
import com.shhm.system.mapper.SysUserRoleMapper;
import com.shhm.system.service.SysUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JackZ
 * @version 1.0
 * @description: 权限管理实现层
 * @date 2025/7/16 下午3:17
 */
@Service
public class SysUserRoleSeviceImpl implements SysUserRoleService {
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public AjaxResult getPermission(Long uid) {
        List<UserRole> userRoles = sysUserRoleMapper.selectRolesByUserId(uid);
        return AjaxResult.success(userRoles);
    }

    @Override
    public List<SysMenu> getRouterList(Long uid) {
        List<SysMenu> routerList = sysUserRoleMapper.selectMenuByUser(uid);
        // 1. 将菜单列表转换为 Map，便于查找
        Map<Long, SysMenu> menuMap = new HashMap<>();
        for (SysMenu menu : routerList) {

            menuMap.put(menu.getMenuId(), menu);
        }

        // 2. 构建父子关系
        List<SysMenu> rootMenus = new ArrayList<>();

        for (SysMenu menu : routerList) {
            Long parentId = menu.getParentId();

            if (parentId == 0) {
                // 如果是根节点 或 父节点不存在，加入根菜单
                rootMenus.add(menu);
            } else {
                // 否则找到父节点，加入其 children
                SysMenu parentMenu = menuMap.get(parentId);
                if (parentMenu != null) {
                    parentMenu.createChildrenList();
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        return rootMenus;
    }
}
